package com.xw.unification.entity.request;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author qiwei
 * @since v1.0.0
 */
public final class RepeatableRequestDelegate {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepeatableRequestDelegate.class);

    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private static final int DEFAULT_BYTE_ARRAY_LENGTH = 1024 * 4;

    public static String stringfy(ServletInputStreamWrapper inputStreamWrapper, Charset charset) {
        if (inputStreamWrapper == null) {
            LOGGER.error("ServletInputStreamWrapper is null");
            return null;
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[DEFAULT_BYTE_ARRAY_LENGTH];
        int length = -1;
        try {
            while ((length = inputStreamWrapper.read(bytes)) >= 0) {
                outputStream.write(bytes, 0, length);
            }
            return outputStream.toString(charset.name());
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding exception, charset name: {}", charset.name());
            return null;
        } catch (IOException e) {
            LOGGER.error("ServletInputStreamWrapper reading exception");
            return null;
        }
    }

    public static boolean rewrite(HttpServletRequest request, byte[] data) {
        if (request instanceof CopyOnReadHttpServletRequest) {
            CopyOnReadHttpServletRequest req = (CopyOnReadHttpServletRequest) request;
            req.rewrite(data);
            return true;
        } else {
            if (request == null) {
                LOGGER.error("Request is null");
            } else {
                LOGGER.error("Request can not be overwrote, request type: {}", request.getClass().getCanonicalName());
            }
            return false;
        }
    }

}
